package com.example.bysj.Dao;
//201902104061徐中堂
import com.example.bysj.domain.authority.Role;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
//声明数据库访问类
@Repository("roleDao")
public class RoleDao {
    //自动注入
    @Autowired
    private JdbcTemplate jdbcTemplate;
    //根据id查角色
    public Role getRoleById(int role_id){
        String sql = "SELECT * FROM role WHERE id=?";
        List<Role> roles = jdbcTemplate.query(sql, new Object[]{role_id}, new RowMapper<Role>() {
            @Override
            public Role mapRow(ResultSet rs, int rowNum) throws SQLException {
                return new Role(
                        rs.getInt("id"),
                        rs.getString("role"),
                        rs.getString("description"),
                        rs.getInt("avaliable"),
                        null
                );
            }
        });
        if (!roles.isEmpty()){
            return roles.get(0);
        }else {
            return null;
        }
    }

    //增加
    public boolean add(Role role) {
        String sql = "INSERT INTO Role (role,description,avaliable) VALUES (?,?,?)";
        int affectedRowNum = jdbcTemplate.update(sql, role.getRole(),
                role.getDescription(),role.getAvaliable());
        if (affectedRowNum != 1) {
            return false;
        } else {
            return true;
        }
    }
    public List<Role> findAll(){
        String sql = "SELECT * FROM Role";

        List<Role> roles = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(Role.class){

        });
        return roles;
    }
    public boolean update(Role role){
        String sql = "UPDATE Role SET role = ? ,description=? ,avaliable=?WHERE id = ?";
        int affectedRowNum = jdbcTemplate.update(sql,role.getRole(),role.getDescription(),role.getAvaliable(),role.getId());
        if (affectedRowNum!=1){
            return false;
        }else{
            return true;
        }
    }
    public boolean delete(int id){
        String sql = "DELETE FROM Role WHERE id = ? ";
        int affectedRowNum = jdbcTemplate.update(sql,id);
        if (affectedRowNum!=1){
            return false;
        }else{
            return true;
        }
    }
}
